// Gestionnaire assembler par anthony d'Alchimiste M&W
/**
 * CMS - jQuery plugin 
 *
 * Copyright (c) 2011-2012 Benoit Racine, 2011 Alchimiste Musique et Web (QC/CAN)
 * http://code.google.com/p/the-alchimist-generator/
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 */

	function recupSite(){
		$.ajax({
			type: "POST" ,
			async: false,
			url: "gestionnaire/requeteBD.php",
			data: "section=all&action=get",
			processData: false ,
			success: function(msg){ initiation(msg); }
		});
	}
	
	function initiation(siteStr){
		while(siteStr != ""){
			sec = siteStr.slice(0, siteStr.indexOf("_~¤¬_"));
			pos = siteStr.slice(siteStr.indexOf("_~¤¬_")+5, siteStr.indexOf("¤~°¬¤"));
			contenu = siteStr.slice(siteStr.indexOf("¤~°¬¤")+5, siteStr.indexOf("°¬¤~°"));
			id = "#"+ sec +"-"+ pos;
			siteStr = siteStr.slice(siteStr.indexOf("°¬¤~°")+5);
			if(document.getElementById(id)!=null){ $(id).html(contenu); }
			else {
				sec = sec.substr(0, sec.indexOf("_")+1);
				for(i=0;i<arrLng.length;i++){
					tmpId = sec + arrLng[i] +"-"+ 1;
					newId = sec + arrLng[i] +"-"+ pos;
					if(document.getElementById(newId)==null){ $("#"+tmpId).clone().attr("id", newId).appendTo(document.getElementById(tmpId).parentNode); }
				}
				$(id).html(contenu);
			}		
		}
		
		sec = "sec" + location.hash.substring(3, location.hash.indexOf("-"));
		lng = location.hash.substr(location.hash.indexOf("-")+1);
		if(sec=="sec"){
			sec = "sec1";
			lng = "frn";
		}
		$("."+ lng).show();
		$("#"+ sec).show();
		$("#menu").data("menu", sec).data("lng", lng);
		menu();
		login();
	}
	
	function getEleBD(id){
		phpData = "section="+id.substring(1,id.indexOf("-"))+"&position="+id.substring(id.indexOf("-")+1)+"&action=get";
		$.ajax({
			data: phpData,
			success: function(msg){ res = msg; },
			type: "POST",
			url: "gestionnaire/requeteBD.php"
		});
		return res;
	}
	
	function insEle(id){
		msgBD = getEleBD(id); 
		if( msgBD != "vide"){
			$(id).html(msgBD);
		}
	}

	$(function() {
    	$('#wysiwyg').wysiwyg({
    		controls: {
				saver: {
					visible: true,
					exec: function() {
						if($("#wswg").data("admin")==true){
							var dataHtml = modTxt($('#wysiwyg').wysiwyg('getContent'));
							var id = $(".vs-context-menu").data("wysid");
							var sec = id.substring(1, id.indexOf("-"));
							var pos = id.substr(id.indexOf("-")+1);
							$.jqDialog.confirm("Etes-vous sur de vouloir sauvegarder ce texte?",
								function() { 
									$.ajax({
									type: "POST",
									url: "gestionnaire/requeteBD.php",
									data: "html="+ dataHtml +"&section="+ sec +"&position="+ pos +"&action=save",
									success: function(msg){ alert(msg); }
								});
								}, // callback function for 'YES' button
								function() {}	 // callback function for 'NO' button
							);
						} else {
							alert("vous n'avez pas la permission d'utiliser la fonction de sauvegarde");
						}
					},
					className: 'saver',
					tags: ['saver'],
					tooltip: 'Enregistrer'
				},	
				check: {
					visible: true,
					exec: function() { fermerWswg(); },
					className: 'check',
					tags: ['check'],
					tooltip: 'insertion'
				}
	    	}
		});
	});

	function modTxt(mod){
		if(/&lt;/.test(mod) || /&gt;/.test(mod)){ mod = mod.replace(/&gt;/gi, ">").replace(/&lt;/gi, "<"); }
		if(/<-frm-/i.test(mod)){ mod = mod.replace(/<-frm-/gi, "<iframe").replace(/-frm->/gi, "</iframe>"); }
		else if (/href/i.test(mod) && /<img/i.test(mod)){ mod = mod.replace(/href/g, "target='blank' href").replace(/<br>/g, ""); }
		else { mod = mod.replace(/href/g, "target='blank' href"); }
		if(/&nbsp;/.test(mod)){ mod = mod.replace(/&nbsp;/g, " "); }
		return mod;
	}

	function fermerWswg(){
		allowedit=true;
		id = $(".vs-context-menu").data("wysid");
		newId = id.substring(0, id.indexOf("-")+1)+($(id).data("lastDiapo")+1);
		contenu = modTxt($('#wysiwyg').wysiwyg('getContent'));
		$("#overshadow").hide();
		$("#gestion").append($("#wswg, #uploadImg"));
		if($(id).hasClass("vidUpl")&& /<!--/i.test(contenu)){ console.log("video"); $(id).html(contenu.substr(3));
		} else { $(id).html(contenu); }
	}
	
	function validate() {
		pw = b64_md5(document.loginform.pword.value);
		
		$.ajax({
			type: "POST",
			url: "gestionnaire/requeteBD.php",
			data: "login="+pw+"&action=login",
			success: function(msg){
				if(msg=="tous"){
					initContextMenu();
					$("#show-Login").css("color", "#3b9e2e");
				}
				if(msg =="admin"){
					$("#wswg").data("admin", true);
					initContextMenu();
					$("#show-Login").css("color", "#F00");
				}
				document.loginform.pword.value = "";
			}
		});
		$("#login").hide("fast");
		$("#show-Login").show("fast");
	}

	function initContextMenu(){
		if($("#show-Login").data("logged")!= true){
			allowedit=true;
			$(".wswg-grp").live("click", function(e){
				$(this).vscontext({menuBlock: 'vs-context-menu'});
				$(".vs-context-menu").data("wysid", "#"+ $(this).attr("id"));
				e.stopPropagation();
			});
			$(".vs-context-menu a").click(function () {
				id = $(".vs-context-menu").data("wysid");
				sec = $(this).attr("id");
				if(sec=="menu_1"){ newDiv(id); }
				else if(sec=="menu_2"){ delDiv(id); }
				else if(sec=="menu_3"){ contextMenuClick(id); }
			});	
			$("#show-Login").data("logged", true);		
		}
	}
	
	function newDiv(id){
		lng = $("#menu").data("lng");
		nbr = id.indexOf("-");
		tmpId = id.substring(1, id.indexOf("_"));
		sec = id.substr(1, nbr);
		pos = parseInt(id.substr(nbr+1));
		do {
			pos++;
			newId = sec + pos;
		}
		while(document.getElementById(newId)!=null);
		sec = document.getElementById(id.substr(1)).parentNode;
		if(newId != "NaN"){
			if($(id).hasClass("phoUpl")){ 
				$(id).clone().attr("id", newId).html("<img src='img/ajoutPhoto.gif' title='nouvelle photo' width='200' height='200' />").appendTo(sec);
			} else if($(id).hasClass("vidUpl")){
				$(id).clone().attr("id", newId).html("Nouvelle section video/ new video section").appendTo(sec);
			} else {
				contenu= "Nouvelle/New section";
				$(id).clone().attr("id", newId).html(contenu).appendTo(sec);
				for(i=0;i<arrLng.length;i++){
					if(lng != arrLng[i]){
						newId = tmpId+"_"+ arrLng[i] +"-"+ pos;
						$(id).clone().attr("id", newId).removeClass(lng).addClass(arrLng[i]).html(contenu).hide().appendTo(sec);
					}
				}
			}
		} else { alert("Vous ne pouvez pas effacer cette section"); }
	}
	
	function delDiv(id){
		sec = id.substring(0, id.indexOf("_")+1);
		pos = id.substr(id.indexOf("-")+1);
		if(pos==1){ alert("Vous ne pouvez pas effacer cette section"); }
		else { 
			$.jqDialog.confirm("Etes-vous sur de vouloir effacer cette section?",
				function() { 
					for(i=0;i<arrLng.length;i++){
						id = sec + arrLng[i] + "-" + pos;
						$(id).remove();
						$.ajax({
							type: "POST",
							url: "gestionnaire/requeteBD.php",
							data: "section="+ sec.substr(1) + arrLng[i] +"&position="+ pos +"&action=del",
							success: function(msg){}
						});						
					}
				}, // callback function for 'YES' button
    			function() {}	 // callback function for 'NO' button
			);
		}
	}
	
	function contextMenuClick(id){
		if(allowedit==true){
			contenu = $(id).html();
			if($(id).hasClass("wswgIns")) {
				$(".wysiwyg").width("auto").height("auto");
				$(".wysiwyg > iframe").width("98%").height($(id).height()+15);
				$(id).html($("#wswg"));
			} else {
				$('.wysiwyg').width(700).height(500);
				$('.wysiwyg > iframe').width("98%").height("93%");
				$("#contentOvr").html($("#wswg"));
				$("#overshadow").show();
			 	if($(id).hasClass("phoUpl")){ $("#uploadImg").show(); }
				else if($(id).hasClass("vidUpl") && /<iframe/.test(contenu)){ contenu = contenu.replace(/<iframe/gi, "<-frm-").replace(/<\/iframe>/gi, "-frm->"); }
			}
			$("#wysiwyg").wysiwyg('setContent', contenu);
			$('html, body').animate({scrollTop: '0px'}, 800);
			allowedit=false;
		} else { alert("Veuillez fermer le gestionnnaire qui est ouvert dans une autre section ou rafraichir la page si vous ne le trouver pas"); }
	}
	
	function login(){
		$("#show-Login").click(function () { 
			$("#login").show();
			$("#show-Login").hide(); 
		});
	}
	
	
/*** Script from http://www.coursesweb.net/ajax ***/
	
	// gets data from the form and sumbit it
	function uploadimg(theform){
		theform.submit();
	
		// calls the function to display Status loading
		$("textarea.wysiwyg").wysiwyg('setContent', "Téléchargement ...");
		return false;
	}
	
	// this function is called from the iframe when the php return the result
	function doneloading(rezultat) {
		// decode (urldecode) the parameter wich is encoded in PHP with 'urlencode'
		rezultat = decodeURIComponent(rezultat.replace(/\+/g,  " "));
	
		// add the value of the wywsiwyg textarea
		//document.getElementById('showimg').innerHTML = rezultat;
		$("textarea.wysiwyg").wysiwyg('setContent', rezultat);
	}
	
	// displays status loading
	function setStatus(theStatus, theloc) {
		var tag = document.getElementById(theloc);
	
		// if there is "tag"
		if (tag) {
			// adds 'theStatus' inside it
			tag.innerHTML = '<b>'+ theStatus + "</b>";
		}
	}